import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Product, ProductService, Comment } from '../shared/product.service';
import { WebSocketService } from '../shared/web-socket.service';
@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {
  product: Product
  comments: Comment[]
  newRating: number = 5;
  newComment: string
  isCommentHidden = true
  isWatched: boolean = false
  currentBid: number
  subscription: any
  constructor(private routeInfo: ActivatedRoute, private productService: ProductService, private wsService: WebSocketService) { }

  ngOnInit() {
    let productId: number = this.routeInfo.snapshot.params['productId']
    this.productService.getProduct(productId).subscribe(
      product => {
        this.product = product
        this.currentBid = product.price
      }
    )
    this.productService.getCommentsForProductId(productId).subscribe(
      comments => this.comments = comments
    )


  }
  sendMessageToServer() {
    this.wsService.sendMessage("hello from client")
  }
  addComment() {
    let comment = new Comment(0, this.product.id, new Date().toISOString(), "someone", this.newRating, this.newComment)
    this.comments.unshift(comment)
    this.newComment = null
    this.newRating = 5
    this.isCommentHidden = true

    let sum = this.comments.reduce((sum, comment) => sum + comment.rating, 0)
    this.product.rating = sum / this.comments.length
  }
  watchProduct() {
    if (this.subscription) {
      this.subscription.unsubscribe()
      this.isWatched = false
      this.subscription = null
    } else {
      this.isWatched = true
      this.subscription = this.wsService.createObservableSocket('ws://localhost:8085', this.product.id).subscribe(
        // data => console.log(data),
        // err => console.log(err),
        // () => { console.log('流已经结素') }
        products => {
          let obj = JSON.parse(products)
          console.log(obj)
          console.log(this.product)
          let product = obj.find(p => p.productId === this.product.id)
          console.log(product)
          this.currentBid = product.bid
        }
      )
    }
  }
}
